package com.shanling.shanlingcontroller.ui.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;

import com.qualcomm.qti.libraries.gaia.GAIA;
import com.shanling.shanlingcontroller.CustomApplication;
import com.shanling.shanlingcontroller.R;
import com.shanling.shanlingcontroller.base.BaseLazyFragment;
import com.shanling.shanlingcontroller.bean.Constants;
import com.shanling.shanlingcontroller.bean.EventCenter;
import com.shanling.shanlingcontroller.services.csr.MainGaiaManager;
import com.shanling.shanlingcontroller.ui.activity.BluetoothCodingActivity;
import com.shanling.shanlingcontroller.ui.activity.GainSettingActivity;
import com.shanling.shanlingcontroller.utils.ThreadPoolProxyFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by ch1 on 2019/11/29.
 */

public class BleStatusFragment extends BaseLazyFragment implements MainGaiaManager.MainGaiaManagerListener, CompoundButton.OnCheckedChangeListener, SeekBar.OnSeekBarChangeListener {
    @BindView(R.id.iv_ble)
    ImageView ivBle;
    @BindView(R.id.tv_blename)
    TextView tvBlename;
    @BindView(R.id.tv_Battery)
    TextView tvBattery;
    @BindView(R.id.tv_bletype)
    TextView tvBletype;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.sw_rgb)
    Switch swRgb;
    @BindView(R.id.sw_HWA)
    Switch swHWA;
    @BindView(R.id.Sb)
    SeekBar Sb;
    @BindView(R.id.rl_code)
    RelativeLayout rlCode;
    @BindView(R.id.rl_gain)
    RelativeLayout rlGain;
    @BindView(R.id.iv_Battery)
    ImageView ivBattery;
    Unbinder unbinder;
    private MainGaiaManager mGaiaManager;
    private boolean isCharging = false;
    private int mBatteryLevel = -1;
    private byte code = 0;
    private byte gainSetting = 1;
    private boolean isSend;
    private Runnable runnable;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        @GAIA.Transport int transport = GAIA.Transport.BR_EDR;
        mGaiaManager = new MainGaiaManager(this, transport);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onLazyLoad() {

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_blestatus;
    }

    @Override
    protected void initViewsAndEvents() {
        Sb.setMax(20);
        tvBlename.setText(preferenceUtil.getBleName());
        swRgb.setOnCheckedChangeListener(this);
        swHWA.setOnCheckedChangeListener(this);
        Sb.setOnSeekBarChangeListener(this);

    }

    @Override
    public void onResume() {
        super.onResume();
        getInformationFromDevice();
    }

    @Override
    public void onPause() {
        super.onPause();
        getRSSINotifications(false);
    }

    private void getInformationFromDevice() {
        mGaiaManager.getInformation(MainGaiaManager.Information.API_VERSION);
        mGaiaManager.getInformation(MainGaiaManager.Information.BATTERY);
        mGaiaManager.getInformation(MainGaiaManager.Information.LED);
        mGaiaManager.getInformation(MainGaiaManager.Information.HWA);
        mGaiaManager.getInformation(MainGaiaManager.Information.CODING);
        mGaiaManager.getInformation(MainGaiaManager.Information.GAIN);
        mGaiaManager.getInformation(MainGaiaManager.Information.CHANNEL);
        mGaiaManager.getInformation(MainGaiaManager.Information.FILTER);
        getRSSINotifications(true);
    }


    private void getRSSINotifications(boolean notify) {
        if (notify) {
            // it is not possible to use the BLE way so we use GAIA
            mGaiaManager.getNotifications(MainGaiaManager.Information.BATTERY, true);
        } else {
            mGaiaManager.getNotifications(MainGaiaManager.Information.BATTERY, false);
        }
    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected void onEventComing(EventCenter eventCenter) {
    }

    @Override
    public boolean sendGAIAPacket(byte[] packet) {
        runnable = new Runnable() {
            @Override
            public void run() {
                isSend = CustomApplication.getInstance().getmGAIABREDRProvider().sendGAIAUpgradePacket(packet, true);
                Log.e("weiyu", "state发送" + isSend);
            }
        };
        ThreadPoolProxyFactory.getNormalThreadPoolProxy().execute(runnable);
        return true;
    }

    @Override
    public void onGetLedControl(boolean activate) {
        Log.e("weiyu", "activi" + activate);
        swRgb.setChecked(activate);
    }

    @Override
    public void onFeatureSupported(int feature) {

    }

    @Override
    public void onInformationNotSupported(int information) {

    }

    @Override
    public void onChargerConnected(boolean isConnected) {
        isCharging = isConnected;
        //refreshBatteryLevel();


    }

    @Override
    public void onGetBatteryLevel(int level) {
        mBatteryLevel = level;
        refreshBatteryLevel();
    }

    private void refreshBatteryLevel() {
        // The battery level to display depends on a percentage, we calculate the percentage.
        int value = mBatteryLevel * 100 / 4250;
        if (value > 100) {
            value = 100;
        }
        tvBattery.setText(value + "%");
        if(value>=90){
            ivBattery.setImageResource(R.drawable.status_icon_battery_n);
        }else if(value>=80&&value<90){
            ivBattery.setImageResource(R.drawable.status_icon_battery_eighty_n);
        }else if(value>=60&&value<80){
            ivBattery.setImageResource(R.drawable.status_icon_battery_sixty_n);
        }else if(value>=40&&value<60){
            ivBattery.setImageResource(R.drawable.status_icon_battery_fourty_n);
        }else {
            ivBattery.setImageResource(R.drawable.status_icon_battery_twenty_n);
        }
        Log.e("weiyu", "获取了" + value);
    }

    @Override
    public void onGetRSSILevel(int level) {


    }

    @Override
    public void onGetAPIVersion(int versionPart1, int versionPart2, int versionPart3) {
        Log.e("weiyu", "得到的版本" + versionPart1 + "." + versionPart2 + "." + versionPart3);
        String APIText = versionPart1 + "." + versionPart2 + "." + versionPart3;
        tvVersion.setText(getString(R.string.version_code) + ": " + APIText);
    }

    @Override
    public void onFeaturesDiscovered() {

    }

    @Override
    public void onGetHWAISAuto(boolean isAuto) {
        Log.e("weiyu", "isAuto" + isAuto);
        swHWA.setChecked(isAuto);

    }

    @Override
    public void onGetBlutoothCode(byte date) {
        code = date;
        Log.e("weiyu", "code" + code);
    }

    @Override
    public void onGetGainSetting(byte selector) {
        gainSetting = selector;
        Log.e("weiyu", "selector" + selector);
    }

    @Override
    public void onGetChannel(byte channel) {
        Log.e("weiyu", "channel" + channel);
        if (channel <= 10) {
            Sb.setProgress(10 - ((int) channel));
        } else {
            Sb.setProgress((int) channel);
        }
    }

    @Override
    public void onGetFilter(byte filterMode) {
        Log.e("weiyu", "filterMode" + filterMode);
        preferenceUtil.setFilter(filterMode + "");

    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(EventCenter eventCenter) {
        switch (eventCenter.getEventCode()) {
            case Constants.GAIA_PACKET:
                byte[] data = (byte[]) eventCenter.getData();
                mGaiaManager.onReceiveGAIAPacket(data);
                break;
            case Constants.GAIA_BLUTOOTH_CODE:
                byte[] blutooth_code = (byte[]) eventCenter.getData();
                code = blutooth_code[0];
                Log.e("weiyu", "得到code" + code);
                mGaiaManager.setBlutoothCoding(blutooth_code);
                break;
            case Constants.GAIN_SETTING:
                byte setting = (byte) eventCenter.getData();
                gainSetting = setting;
                mGaiaManager.setGainSetting(setting);
                break;
            case Constants.SETFILTER:
                byte filter = (byte) eventCenter.getData();
                preferenceUtil.setFilter(filter + "");
                mGaiaManager.setFilter(filter);
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (runnable != null) {
            ThreadPoolProxyFactory.getNormalThreadPoolProxy().remove(runnable);
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        int id = buttonView.getId();
        switch (id) {
            case R.id.sw_rgb:
                mGaiaManager.setLedState(isChecked);
                break;
            case R.id.sw_HWA:
                mGaiaManager.setHWAState(isChecked);
                break;
        }
    }

    @OnClick({R.id.rl_code, R.id.rl_gain})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_code:
                Bundle bundle = new Bundle();
                bundle.putByte("code", code);
                readyGo(BluetoothCodingActivity.class, bundle);
                break;
            case R.id.rl_gain:
                Bundle b = new Bundle();
                b.putByte("gainSetting", gainSetting);
                readyGo(GainSettingActivity.class, b);
                break;
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (progress <= 10) {
            mGaiaManager.setChannel((byte) (10 - progress));
        } else {
            mGaiaManager.setChannel((byte) progress);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }

}
